package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.dao.InvitationDao;
import org.example.entity.ClanDetail;
import org.example.entity.Invitation;
import org.example.entity.User;
import org.example.exception.PermissionsDenyException;
import org.example.exception.SenderIdException;
import org.example.service.ClanService;
import org.example.service.InvitationService;
import org.example.vo.InvitationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import static org.example.interceptor.LoginInterceptor.threadLocal;
@Service
public class InvitationServiceImpl extends ServiceImpl<InvitationDao, Invitation> implements InvitationService {
    @Autowired
    ClanService clanService;
    @Autowired
    ClanDetailServiceImpl  clanDetailService;
    @Override
    public void sendInvitation(InvitationVo invitationVo) throws PermissionsDenyException, SenderIdException {
        User user = threadLocal.get();
        if(invitationVo.getSender()!=user.id) throw new SenderIdException();
        ClanDetail one = clanDetailService.getOne(new QueryWrapper<ClanDetail>().eq("exits", 1).eq("user_id", user.id).eq("role", 1));
        if(one==null) throw new PermissionsDenyException();
        Invitation invitation = new Invitation(invitationVo);
        saveOrUpdate(invitation);
    }

    @Override
    public List<InvitationVo> checkAllReceive(){
        User user = threadLocal.get();
        List<Invitation> receiver = list(new QueryWrapper<Invitation>().eq("receiver", user.id));
        return voFilter(receiver);
    }

    @Override
    public void receiveInvitation(int invitationId) throws PermissionsDenyException {
        User user = threadLocal.get();
        Invitation invitation = getOne(new QueryWrapper<Invitation>().eq("id", invitationId));
        //TODO 订单检查
        if(user.getId()!= invitation.receiver) throw new PermissionsDenyException();
        clanService.combineFamily(invitation.sender,invitation.receiver);
    }

    public List<InvitationVo> voFilter(List<Invitation> list){
        List<InvitationVo> volist =  new ArrayList<>();
        for (Invitation invitation:list
             ) {
            volist.add(new InvitationVo(invitation));
        }
        return volist;
    }

}
